<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('新增文章')"/>
    <th:block th:include="include :: summernote-css"/>
    <th:block th:include="include :: bootstrap-fileinput-css"/>
    <th:block th:include="include :: select2-css"/>
    <script th:inline="javascript">
        var ctx = /*[[${#request.getContextPath()}]]*/ '';
        var serverUrl = /*[[${#httpServletRequest.scheme + "://" + #httpServletRequest.serverName + ":" + #httpServletRequest.serverPort}]]*/ '';
    </script>
</head>
<style>
    .hidden {
        display: none;
    }
</style>
<body class="white-bg">

<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-knowledgepool-add">

        <label class="col-sm-3 control-label">文件类型</label>
        <div class="col-sm-9">
            <label class="radio-box">
                <input type="radio" checked="" value="1" id="optionsRadios1" name="type"
                       onchange="toggleDiv()">文本</label>
            <label class="radio-box">
                <input type="radio" value="2" id="optionsRadios2" name="type" onchange="toggleDiv()">文件</label>
        </div>

        <div class="form-group">
            <label class="col-sm-3 control-label">标题：</label>
            <div class="col-sm-8">
                <input name="title" class="form-control" type="text">
            </div>
            <div></div>
            <label class="col-sm-3 control-label">关键词：</label>
            <div class="col-sm-8">
                <input name="keyword" class="form-control" type="text">
            </div>
            <div></div>
            <label class="col-sm-3 control-label">文章权限标识：</label>
            <div class="col-sm-8">
                <select class="form-control" id="permissionType" name="permissionType"
                        onchange="toggleCustomerSelect()">
                    <!-- 选项将通过 JavaScript 动态加载 -->
                </select>
            </div>
        </div>

        <!-- 修改部门选择部分 -->
        <div class="form-group" id="customerSelectDiv" style="display:none;">
            <label class="col-sm-3 control-label">选择可见部门：</label>
            <div class="col-sm-8">
                <select class="form-control select2" id="deptSelect" multiple>
                    <!-- 选项将通过 JavaScript 动态加载 -->
                </select>
                <input id="deptList" name="deptList" type="hidden">
            </div>
        </div>

        <div id="textDiv" class="hidden">
            <div class="form-group">
                <label class="col-sm-3 control-label">内容：</label>
                <div class="col-sm-8">
                    <input type="hidden" class="form-control" name="content">
                    <div class="summernote" id="content"></div>
                </div>
            </div>
        </div>

        <div id="fileDiv" class="hidden">
            <div class="ibox-content">
                <div class="form-group">
                    <label class="font-noraml">文件上传</label>
                    <div class="file-loading">
                        <input id="multipleFiles" multiple name="files" type="file">
                    </div>
                </div>
            </div>
        </div>




    </form>
</div>

<th:block th:include="include :: footer"/>
<th:block th:include="include :: summernote-js"/>
<th:block th:include="include :: bootstrap-fileinput-js"/>
<th:block th:include="include :: select2-js"/>
<script th:inline="javascript">
    var urls = [];
    var fileNames = [];
    var newFileNames = [];
    var originalFilenames = [];

    function toggleDiv() {
        var fileDiv = document.getElementById('fileDiv');
        var textDiv = document.getElementById('textDiv');
        var selectedInput = document.querySelector('input[name="type"]:checked');
        if (selectedInput != null) {
            var selectedValue = selectedInput.value;
            console.log("selectedValue:", selectedValue);
            if (selectedValue === '2') {  //文件
                fileDiv.classList.remove('hidden');
                textDiv.classList.add('hidden');
            } else if (selectedValue === '1') {  //文本
                fileDiv.classList.add('hidden');
                textDiv.classList.remove('hidden');
            }
        } else {
            console.log("No radio input selected.");
        }
    }

    function toggleCustomerSelect() {
        var permissionType = $("#permissionType").val();
        var customerSelectDiv = $("#customerSelectDiv");

        if (permissionType === "客户类") {  // 使用"客户类"字典标签
            customerSelectDiv.show();
            $("#deptSelect").attr("required", "required");
            loadDeptOptions();
        } else {
            customerSelectDiv.hide();
            $("#deptSelect").removeAttr("required");
            $("#deptSelect").empty().trigger('change');
        }
    }

    // 页面加载完毕时触发
    window.onload = function () {
        // 设置初始显示为文本
        toggleDiv('1');

        // 监听单选框选择变化
        var radios = document.querySelectorAll('input[name="type"]');
        for (var i = 0; i < radios.length; i++) {
            radios[i].addEventListener('change', function () {
                toggleDiv(this.value);
            });
        }
    };
    var prefix = ctx + "system/knowledgepool"
    $("#form-knowledgepool-add").validate({
        focusCleanup: true
    });

    function loadDeptOptions() {
        $.ajax({
            url: ctx + "system/dept/list",
            type: "POST",
            dataType: "json",
            success: function (result) {
                console.log("API返回结果:", result);
                var deptSelect = $("#deptSelect");
                deptSelect.empty();

                if (result && result.length > 0) {
                    // 按照parentId组织部门树结构
                    var deptMap = {};
                    var topDepts = [];

                    // 首先建立映射关系
                    $.each(result, function (index, dept) {
                        dept.children = [];
                        deptMap[dept.deptId] = dept;
                    });

                    // 构建树形结构
                    $.each(result, function (index, dept) {
                        if (dept.parentId === "0") {
                            topDepts.push(dept);
                        } else {
                            var parent = deptMap[dept.parentId];
                            if (parent) {
                                parent.children.push(dept);
                            }
                        }
                    });

                    // 递归添加选项
                    function addOptions(depts, level) {
                        $.each(depts, function (index, dept) {
                            // 创建缩进
                            var indent = "";
                            for (var i = 0; i < level; i++) {
                                indent += "　";  // 使用全角空格作为缩进
                            }
                            if (level > 0) {
                                indent += "├─ ";
                            }

                            // 添加选项
                            deptSelect.append(new Option(indent + dept.deptName, dept.deptId, false, false));

                            // 递归处理子部门
                            if (dept.children && dept.children.length > 0) {
                                addOptions(dept.children, level + 1);
                            }
                        });
                    }

                    // 开始递归添加选项
                    addOptions(topDepts, 0);
                } else {
                    deptSelect.append(new Option("暂无可选部门", "", false, false));
                }

                deptSelect.trigger('change');
            },
            error: function (xhr, status, error) {
                console.error("请求失败:", {
                    status: status,
                    error: error,
                    response: xhr.responseText
                });
                $.modal.alertError("加载部门列表失败");
            }
        });
    }

    function submitHandler() {
        if ($.validate.form()) {
            var permissionType = $("#permissionType").val();
            if (permissionType === "客户类") {
                var selectedDepts = $("#deptSelect").val();
                if (!selectedDepts || selectedDepts.length === 0) {
                    $.modal.alertWarning("请选择可见部门");
                    return;
                }
                $("#deptList").val(selectedDepts.join(','));
            }

            var selectedType = $("input[name='type']:checked").val();

            if (selectedType === '2' && urls.length > 0) {
                // 将所有文件信息合并为一个请求
                var formData = $('#form-knowledgepool-add').serialize();
                formData += "&urls=" + urls.join(',');
                formData += "&fileNames=" + fileNames.join(',');
                formData += "&newFileNames=" + newFileNames.join(',');
                formData += "&originalFilenames=" + originalFilenames.join(',');

                $.operate.save(prefix + "/add", formData);
            } else {
                var bady = $('#form-knowledgepool-add').serialize();
                $.operate.save(prefix + "/add", bady);
            }
        }
    }

    $(function () {
        $('.summernote').summernote({
            lang: 'zh-CN',
            minHeight: 600,
            widths: 500,
            dialogsInBody: true,
            callbacks: {
                onChange: function (contents, $edittable) {
                    $("input[name='" + this.id + "']").val(contents);
                },
                onImageUpload: function (files) {
                    var obj = this;
                    var data = new FormData();
                    data.append("file", files[0]);
                    $.ajax({
                        type: "post",
                        url: ctx + "common/upload",
                        data: data,
                        cache: false,
                        contentType: false,
                        processData: false,
                        dataType: 'json',
                        success: function (result) {
                            if (result.code == web_status.SUCCESS) {
                                $('#' + obj.id).summernote('insertImage', result.url);
                            } else {
                                $.modal.alertError(result.msg);
                            }
                        },
                        error: function (error) {
                            $.modal.alertWarning("图片上传失败。");
                        }
                    });
                }
            }
        });
    });
    $(document).ready(function () {
        // 多文件上传
        $("#multipleFiles").fileinput({
            uploadUrl: ctx + 'common/uploads',
            maxFileCount: 10,
            autoReplace: false,
            uploadAsync: false
        }).on('filebatchuploadsuccess', function (event, data, previewId, index) {
            var rsp = data.response;
            console.log("返回数据:", rsp);

            if (rsp.urls) urls = rsp.urls.split(',');
            if (rsp.fileNames) fileNames = rsp.fileNames.split(',');
            if (rsp.newFileNames) newFileNames = rsp.newFileNames.split(',');
            if (rsp.originalFilenames) originalFilenames = rsp.originalFilenames.split(',');

            console.log("上传文件后变量值：", urls, fileNames, newFileNames, originalFilenames);
        }).on('filecleared', function (event) {
            urls = [];
            fileNames = [];
            newFileNames = [];
            originalFilenames = [];
        });

        // 初始化select2
        $("#deptSelect").select2({
            placeholder: "请选择可见部门",
            allowClear: true,
            width: '100%',
            language: "zh-CN",
            multiple: true,
            minimumResultsForSearch: 0,
            templateResult: function (data) {
                // 保持HTML格式
                return data.text;
            }
        });

        // 初始化显示状态
        toggleCustomerSelect();

        // 加载权限类型
        loadPermissionTypes();
    });

    // 添加新的加载权限类型函数
    function loadPermissionTypes() {
        var baseUrl = window.location.protocol + "//" + window.location.host;
        var url = baseUrl + "/system/dict/data/list";

        console.log("使用的完整URL:", url);

        $.ajax({
            url: url,
            type: "POST",
            dataType: "json",
            contentType: "application/x-www-form-urlencoded",
            data: {
                pageSize: 10,
                pageNum: 1,
                orderByColumn: "dictSort",
                isAsc: "asc",
                dictType: "sys_knowledge_permission"
            },
            success: function (result) {
                var permissionSelect = $("#permissionType");
                permissionSelect.empty();

                if (result.rows && result.rows.length > 0) {
                    $.each(result.rows, function (index, dict) {
                        permissionSelect.append(new Option(dict.dictLabel, dict.dictValue));
                    });
                } else {
                    permissionSelect.append(new Option("暂无可选权限类型", "", false, false));
                }

                permissionSelect.trigger('change');
            },
            error: function (xhr, status, error) {
                console.error("请求失败:", {
                    url: url,
                    status: status,
                    error: error,
                    response: xhr.responseText
                });
                $.modal.alertError("加载权限类型失败");
            }
        });
    }
</script>


</body>
</html>